package com.hiyori.hiyorinovel;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String URL = "jdbc:mysql://localhost:3306/novaldata?useSSL=false&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "Hiyori";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String nickname = request.getParameter("nickname");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String invitationCode = request.getParameter("invitationCode");

        // 检查密码是否符合要求（只检查长度）
        if (!isPasswordValid(password)) {
            request.setAttribute("error", "密码长度需超过7位");
            request.getRequestDispatcher("/novel/reg.jsp").forward(request, response);
            return;
        }

        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的密码不匹配");
            request.getRequestDispatcher("/novel/reg.jsp").forward(request, response);
            return;
        }

        try {
            // 使用SHA-256对密码进行哈希加密
            String hashedPassword = hashPassword(password);
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
                String query = "INSERT INTO userdata (username, nickname, email, password, invitationcode) VALUES (?, ?, ?, ?, ?)";
                try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
                    preparedStatement.setString(1, username);
                    preparedStatement.setString(2, nickname);
                    preparedStatement.setString(3, email);
                    preparedStatement.setString(4, hashedPassword);
                    preparedStatement.setString(5, invitationCode.isEmpty() ? null : invitationCode);
                    preparedStatement.executeUpdate();
                }
                response.sendRedirect("../novel/login.jsp");
            }
        } catch (SQLException | NoSuchAlgorithmException | ClassNotFoundException e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库错误");
            request.getRequestDispatcher("../novel/reg.jsp").forward(request, response);
        }
    }

    private String hashPassword(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashedBytes = md.digest(password.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : hashedBytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    // 检查密码是否符合要求（只检查长度）
    private boolean isPasswordValid(String password) {
        return password.length() > 7; // 只检查长度，不再检查特殊字符
    }
}